package com.pub.encryption;

//import java.security.MessageDigest;

public class PublicEncryption {
    public PublicEncryption() {
    }

    /**
     * 將字串加密
     * @param pstrEncryptionType 加密的演算法 ex.MD5 etc,.
     * @param pstrSrcStr String
     * @return String
     */
    public static String getEncryptionString(String pstrEncryptionType,
                                             String pstrSrcStr) {
        try {
            if(pstrEncryptionType!=null && pstrEncryptionType.equals("PUB")){
                return getPubEncryptionString(pstrSrcStr);
            }
            else if(pstrEncryptionType!=null && pstrEncryptionType.equals("NONE")){
                return pstrSrcStr;
            }

            //mark by GM 09/06/16 because warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
//            java.security.MessageDigest md = null;
//            md = MessageDigest.getInstance(pstrEncryptionType);
//            String result = new String(md.digest(pstrSrcStr.getBytes()));
//            return (new sun.misc.BASE64Encoder()).encode(result.getBytes());

            return "Non Suuport EncryptioonType==>" + pstrEncryptionType;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 取得自定加密字串
     *
     * @param pstrSrcStr String 欲加密字串
     * @return String 加密後字串
     */
    public static String getPubEncryptionString(String pstrSrcStr) {
        StringBuffer lstbEncrpty = new StringBuffer();
        try {
            for (int i = 0; i <= pstrSrcStr.length() - 1; i++) {
                lstbEncrpty.append(Integer.toHexString(((int) pstrSrcStr.charAt(
                        i)) + pstrSrcStr.length()));
            }
            return lstbEncrpty.toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 將自定加密字串解密
     *
     * @param pstrEncrptionStr String 欲解密字串
     * @return String
     */
    public static String getPubDeEncrptionString(String pstrEncrptionStr) {
        StringBuffer lstbDeEncrptionStr = new StringBuffer();
        try {
            for (int i = 0; i < pstrEncrptionStr.length(); i += 2) {
                lstbDeEncrptionStr.append((char) (Integer.parseInt(
                        pstrEncrptionStr.substring(i, i + 2), 16) -
                                                  (pstrEncrptionStr.length() /
                        2)));
            }
            return lstbDeEncrptionStr.toString();
        } catch (Exception e) {
            return null;
        }
    }
}
